package portal.monitor.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import org.apache.hadoop.util.Time;

import com.alibaba.fastjson.JSONObject;

import beans.HttpConfig;
import beans.HttpResult;
import beans.TokenValue;
import net.CommitJob;
import net.HttpRequest;
import utils.Log4jInit;
import utils.StaticUtil;

public class ScheUtils {

	public static HttpResult getToken(String userName, String passWord) {
		if (!HttpConfig.fake) {
			String token = TokenValue.TOKEN.getTokenValue(HttpConfig.userName, HttpConfig.passWord);
			if (token != null) {
				return new HttpResult(true, token);
			} else {
				return new HttpResult(false, "服务器错误！");
			}
		} else {
			return new HttpResult(true, "fakeToken");
		}
	}
	/**
	 * 上传一个文件并返回其在ftp的文件位置
	 * 
	 * @param filePath
	 *            本地文件位置
	 * @param ftpFileUri
	 *            ftp文件位置
	 * @return
	 * @throws IOException
	 *             生成脚本文件出错
	 */
	public static String uploadFile(String filePath, String ftpFileUri) throws IOException {
		
		String scriptFileUri = generateScriptFile(ftpFileUri, filePath);
		if (createFolders(ftpFileUri) && runBat(scriptFileUri)) {
			StaticUtil.deleteFile(scriptFileUri);
			return ftpFileUri;
		} else {
			return null;
		}
	}
	
	/**
	 * 生成上传ftp文件的脚本文件
	 * 
	 * @param ftpFileUri
	 *            ftpFile文件路径
	 * @param fileUri
	 *            本地文件路径
	 * @return
	 * @throws IOException
	 */
	private static String generateScriptFile(String ftpFileUri, String fileUri) throws IOException {

		if(fileUri.equals("")||fileUri.equals(null)){
			return "";
		}
		
		String command = MonConfig.fileclient + " -m " + HttpConfig.uploadIP + " -l " + fileUri + " -r " + ftpFileUri
				+ " -u -n jhadmin";
		Log4jInit.logger.info("ftp command::::" + command);
		String scriptFileUri = HttpConfig.scriptFileUri;
		File scriptFile = new File(scriptFileUri);
		if (!scriptFile.exists()) {
			scriptFile.mkdirs();
			MonBaseUtils.chmod(scriptFileUri);
		}
		String scriptUri = scriptFileUri + UUID.randomUUID().toString().substring(0, 20) + ".sh";
		File algorithmBatFile = new File(scriptUri);
		FileWriter fw = new FileWriter(algorithmBatFile);
		MonBaseUtils.chmod(scriptUri);
		fw.write(command);
		fw.close();
		return scriptUri;
	}
	
	private static boolean createFolders(String ftpFileUri) {
		if (!HttpConfig.fake) {
			String targetUri = ftpFileUri.substring(0, ftpFileUri.lastIndexOf("/") + 1);
			String params = "dirpath=" + targetUri + "&isforce=true&token="
					+ getToken(HttpConfig.userName, HttpConfig.passWord).getMessage();
			JSONObject result = JSONObject.parseObject(HttpRequest.sendGet(HttpConfig.createFtpFolder, params));
			if (result.getString("result").equals("success")) {
				return true;
			} else {
				return false;
			}
		} else {
			return true;
		}
	}
	
	/**
	 * run the bat file in batUri
	 *
	 * @param batUri
	 */
	private static boolean runBat(String batUri) {
		boolean result = false;
		if (!HttpConfig.fake) {
			Process p;
			try {
				MonBaseUtils.chmod(batUri);
				// 执行命令
				p = Runtime.getRuntime().exec(batUri);
				// Log4jInit.logger.info("====exec:"+batUri);
				// 取得命令结果的输出流
				InputStream fis = p.getInputStream();
				// 用一个读输出流类去读
				InputStreamReader isr = new InputStreamReader(fis, "gbk");
				// 用缓冲器读行
				BufferedReader br = new BufferedReader(isr);
				String line = null;
				// 直到读完为止
				while ((line = br.readLine()) != null) {
					if (line.equals("upload file success")) {
						result = true;
					}
				}
				File f = new File(batUri);
				f.delete();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return result;
		} else {
			return true;
		}
	}
	
	
	/**
	 * @param commitJob
	 * @return success:jobId fail:message
	 */
	public static HttpResult startJob(CommitJob commitJob) {
		Log4jInit.logger.info("-------START Algrithm TIME : " + Time.now());
		if (!HttpConfig.fake) {
			Log4jInit.logger.info("commitJob param:" + commitJob.getRequestParam());
			String tempResult = HttpRequest.sendPost(HttpConfig.commitJob, commitJob.getRequestParam());
			Log4jInit.logger.info("commitJob result:" + tempResult);
			JSONObject result = JSONObject.parseObject(tempResult);
			SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss");
			Log4jInit.logger.info("-------Task complete::" + sf.format(new Date()));
			if (result.getString("result").equals("success")) {
				String jobId = result.getJSONArray("data").getString(0);
				return new HttpResult(true, jobId);
			} else {
				return new HttpResult(false, result.getString("message"));
			}
		} else {
			return new HttpResult(true, UUID.randomUUID().toString().substring(0, 20));
		}

	}
	
	
	
}
